package token

import (
	"errors"
	"time"

	"gitee.com/hexug/devcloud/mcenter/conf"
	"gitee.com/hexug/devcloud/mcenter/consted"
)

// 创建普通用户的
func NewToken() *Token {
	now := time.Now().Unix()
	return &Token{
		IssueAt:          now,
		AccessExpiredAt:  conf.C().GetInt64("token.timeout"),
		RefreshExpiredAt: conf.C().GetInt64("token.timeout") * 4,
		Status:           &Status{IsBlock: false},
		Namespace:        consted.DEFAULT_NAMESPACE,
		IsAdmin:          false,
		Meta:             map[string]string{},
	}
}

// 创建管理员用户
func NewAdminToken() *Token {
	now := time.Now().Unix()
	return &Token{
		IssueAt:          now,
		AccessExpiredAt:  conf.C().GetInt64("token.timeout"),
		RefreshExpiredAt: conf.C().GetInt64("token.timeout") * 4,
		Status:           &Status{IsBlock: false},
		Namespace:        consted.DEFAULT_NAMESPACE,
		IsAdmin:          true,
		Meta:             map[string]string{},
	}
}

func (t *Token) CheckToken(in *ValidateTokenRequest) error {
	if t.AccessToken == in.AccessToken && t.Username == in.Username {
		return nil
	}
	return errors.New("token校验失败")
}
func (t *Token) CheckStatus() error {
	if t.Status.IsBlock {
		return errors.New("token已冻结")
	}
	if t.Expired() >= 0 {
		return errors.New("token已过期")
	}
	return nil
}

func (t *Token) Expired() time.Duration {
	dura := time.Duration(t.AccessExpiredAt * int64(time.Second))
	ExpiredTime := time.Unix(t.IssueAt, 0).Add(dura)
	return time.Since(ExpiredTime)
}

func (i *IssueTokenRequest) Validate() error {
	switch i.GrantType {
	case GRANT_TYPE_PASSWORD:
		if i.Password == "" || i.Username == "" {
			return errors.New("用户名和密码不能为空")
		}
		return nil
	case GRANT_TYPE_DINGDING:
		return errors.New("dingding provider尚未实现")
	case GRANT_TYPE_FEISHU:
		return errors.New("feishu provider尚未实现")
	case GRANT_TYPE_LDAP:
		return errors.New("ldap provider尚未实现")
	default:
		return errors.New("类型不可用")
	}
}
